package com.bnzj.cloud.business.core.web;

import java.util.List;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import com.bnzj.cloud.business.core.service.SysDictionaryService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.bnzj.cloud.business.core.persistence.entity.SysDictionary;
import com.bnzj.core.action.ActionType;
import com.bnzj.core.action.annotation.Action;
import com.bnzj.core.exception.BusinessException;
import com.bnzj.core.persistence.query.CompareExpression;
import com.bnzj.core.persistence.query.CompareType;
import com.bnzj.core.persistence.query.IExpression;
import com.bnzj.core.persistence.query.QueryHelpBean;
import com.bnzj.core.persistence.util.EntityUtils;
import com.bnzj.core.rest.CurrentUserService;
import com.bnzj.core.rest.ResponseResult;
import com.bnzj.core.rest.ResultCode;
import com.bnzj.core.rest.UserInfo;
import com.bnzj.core.util.BeanUtils;
import com.bnzj.core.webmvc.util.WebMvcUtils;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;

/**
 * @author Barry
 * @createDate 2020/2/14
 * @description
 */
@Tag(name = "SysDictionaryController", description = "字典数据管理")
@RestController
@RequestMapping("/system/dictionary")
public class SysDictionaryController {

    @Autowired
    private CurrentUserService gatewayCurrentUserService;

    @Autowired
    private SysDictionaryService sysDicService;

    @Operation(summary = "分页查询", description = "",
            parameters = {
                    @Parameter(name = "keyWord", description = "关键字查询", allowEmptyValue = true, allowReserved = true, schema = @Schema(implementation = String.class, description = "无"))
            })
    @GetMapping(value = "/page")
    public ResponseResult<Page<SysDictionary>> getDictionaryPage(HttpServletRequest request) {
        Pageable pageable = WebMvcUtils.initPage(request, Sort.by(Sort.Direction.DESC, "create_time"));
        QueryHelpBean queryHelpBean = SysDictionaryService.getQueryHelpBean();
        queryHelpBean.setPageable(pageable);
        //根据字典类型进行查询
        IExpression andCondition1 = CompareExpression.build("d.type_id", CompareType.equal, request.getParameter("typeId"));
        IExpression orCondition1 = CompareExpression.build("d.name", CompareType.like, request.getParameter("keyWord"));
        IExpression andCondition2 = CompareExpression.build("d.deleted", CompareType.equal, false);
        queryHelpBean.addWhere(andCondition1.or(orCondition1).and(andCondition2));
        Page<SysDictionary> page = sysDicService.findAll(queryHelpBean);
        return ResponseResult.success(page);
    }

    @Operation(summary = "查询所有的字典数据")
    @GetMapping(value = "/all")
    public ResponseResult<List<SysDictionary>> getAllDictionary() {
        QueryHelpBean queryHelpBean = SysDictionaryService.getQueryHelpBean();
        Pageable pageable = WebMvcUtils.initPage();
        queryHelpBean.setPageable(pageable);
        List<SysDictionary> list = sysDicService.exportAll(queryHelpBean);
        return ResponseResult.success(list);
    }

    @Operation(summary = "根据id查询")
    @GetMapping("/one/{id}")
    public ResponseResult<SysDictionary> getById(@Parameter(in = ParameterIn.PATH, name = "id", description = "主键", required = true) @PathVariable("id") Long id) {
        Optional<SysDictionary> optional = sysDicService.findById(id);
        return ResponseResult.success(optional.orElse(null));
    }


    @Operation(summary = "保存")
    @Action(descriprion = "字典新增",moduleName = "字典",operateType = ActionType.ADD_DATA)
    @PostMapping("save")
    public ResponseResult<?> addDictionary(@RequestBody @Valid SysDictionary sysDictionary) {
        UserInfo userInfo = gatewayCurrentUserService.getUserInfo();
        EntityUtils.saveBefore(sysDictionary, userInfo.getAccount(), userInfo.getName());
        sysDicService.save(sysDictionary);
        return ResponseResult.success();
    }


    @Operation(summary = "局部更新")
    @Action(descriprion = "字典更新",moduleName = "字典",operateType = ActionType.UPDATE_DATA)
    @PostMapping("/update")
    public ResponseResult<?> updateDictionary(@RequestBody SysDictionary sysDictionary) {
        if (ObjectUtils.isEmpty(sysDictionary.getId())) {
            throw new BusinessException(ResultCode.getResultCode(ResultCode.BAD_REQUEST));
        }
        UserInfo userInfo = gatewayCurrentUserService.getUserInfo();
        Optional<SysDictionary> sysDictionaryOpt = sysDicService.findById(sysDictionary.getId());
        SysDictionary sysDictionaryDb = sysDictionaryOpt.get();
        BeanUtils.copyProperties(sysDictionary, sysDictionaryDb);
        EntityUtils.saveBefore(sysDictionaryDb, userInfo.getAccount(), userInfo.getName());
        sysDicService.save(sysDictionaryDb);
        return ResponseResult.success();
    }


    @Operation(summary = "删除")
    @Action(descriprion = "字典删除",moduleName = "字典",operateType = ActionType.DELETE_DATA)
    @GetMapping("/delete/{id}")
    public ResponseResult<?> delete(@Parameter(name = "id", description = "主键") @PathVariable("id") Long id) {
        sysDicService.deleteById(id);
        return ResponseResult.success("删除成功！");
    }
}
